<template>
  <div class="zs-bind">
     <!-- <div style="height:8%;width:100%;position:fixed;z-index:999;background:#f9f9f9;margin-top: -28px;display:flex;align-item:center;margin-left:-25px;" class="fin_header">
      <div  @click="$router.push('/user/zs_manager')" class="zs_bind_back"><span><i class="el-icon-arrow-left el-icon-left" style="margin-right: 5px;"></i>绑定证书</span></div>
    </div> -->
    <div class="header">
      <div class="header_span">
        <div @click="$router.push('/user/zs_manager')" class="zs_bind_back"><span><i class="el-icon-arrow-left el-icon-left" style="margin-right: 5px;"></i>绑定证书</span></div>
      </div>
    </div>
    <el-card shadow="never">
      <div class="content-top">
        <div class="content-top-left">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top" class="form">
            <el-form-item>
              <span slot="label" prop="pubKey">
                <label>Public key（公钥）</label>
                <label class="key_text"  @click="getSecretKey">生成密钥</label>
                <label v-if="form.pubKey || publicData" class="copy_text" :data-clipboard-text="form.pubKey" @click="copyText">复制</label>
              </span>
              <el-input v-if="!publicData" v-model="form.pubKey" type="textarea" maxlength="300"  style="width:60%;margin-top:8px;"></el-input>
              <el-input v-else v-model="publicData" type="textarea" maxlength="300"  style="width:60%;margin-top:8px;"></el-input>
            </el-form-item>
            <el-form-item prop="priKey">
              <span slot="label">
                <label>Private key（私钥）</label>
                <label v-if="form.priKey || privateData" class="copy_text" :data-clipboard-text="form.pubKey" @click="copyText">复制</label>
              </span>
              <el-input v-if="!privateData" v-model="form.priKey" type="textarea" maxlength="300"  style="width:60%;margin-top:8px;overflow:hidden;"></el-input>
              <el-input v-else v-model="privateData" type="textarea" maxlength="300"  style="width:60%;margin-top:8px;overflow:hidden;"></el-input>
            </el-form-item>
            <el-form-item label="clientId" prop="clientId">
              <el-input v-model.trim="form.clientId"></el-input>
            </el-form-item>
            <el-form-item label="teamId" prop="teamId">
              <el-input v-model.trim="form.teamId"></el-input>
            </el-form-item>
            <el-form-item label="keyId" prop="keyId">
              <el-input v-model.trim="form.keyId"></el-input>
            </el-form-item>
            <el-form-item label="密钥名称" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-button  type="success" :loading="isStatus" size="small" @click="bindZS('form')">绑定密钥</el-button>
          </el-form-item>
          </el-form>
        </div>
        <div class="content-top-right">
          <!-- <el-form label-width="80px" label-position="top" class="form">
            <el-form-item label="如何获取我的API凭据？"> -->
              <p  class="right_title"><i slot="reference" class="iconfont icon-question-circle icon_img" />如何获取我的API凭据？</p>
              <p class="right_title_text">1.生成公钥：</p>
              <p class="title_tip">在3YData<label @click="getSecretKey">生成密钥</label>（Public Key 与 Private Key） </p>
              <p class="right_title_text" >2.生成密钥：</p>
              <p class="title_tip">在Apple Search Ads 后台授权API权限，上传公钥（Public Key）后，生成clientId、teamId、keyId。<label @click="test">点击此处打开Ads后台</label></p>
              <p class="right_title_text">3.同步数据：</p>
              <p class="title_tip">同步数据至3YData:在本页面填写 clientId、teamId、keyId、密钥名称并保存后，即可同步对应ASA数据。</p>
              <p class="right_title_text">注意：API证书权限必须是【API账号经理】，否则将有可能造成数据错乱。 </p>
            <!-- </el-form-item>
          </el-form> -->
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import Clipboard from 'clipboard'
import {
  createSecretKey,
  bindModify
} from '@/api/user.js'
export default {
  name: 'ZsBind',
  data() {
    const validatePubKey = (rule, value, callback) => {
      if (this.publicData === ''  && this.form.pubKey === '') {
        callback(new Error('请输入公钥'))
      } else {
        callback()
      }
    }
    const validatePriKey = (rule, value, callback) => {
      if (this.form.priKey === '' && this.privateData === '') {
        callback(new Error('请输入私钥'))
      } else {
        callback()
      }
    }
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密钥名称'))
      } else {
        callback()
      }
    }
    const validateId = (rule, value, callback) => {
      const reg = /^[^\u4e00-\u9fa5]+$/
      if (value === '') {
        callback(new Error('请输入id'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入有效id'))
      } else {
        callback()
      }
    }
    return {
      form: {
        pubKey: '',
        priKey: '',
        clientId: '',
        teamId: '',
        keyId: '',
        name: '',
        uuid: '',
        isStatus: false,
      },
      rules: {
        pubKey: [{ validator: validatePubKey, trigger: 'blur' }],
        priKey: [{ validator: validatePriKey, trigger: 'blur' }],
        clientId: [{ validator: validateId, trigger: 'blur' }],
        teamId: [{ validator: validateId, trigger: 'blur' }],
        keyId: [{ validator: validateId, trigger: 'blur' }],
        name: [{ validator: validateName, trigger: 'blur' }]
      }
    }
  },
   props: {
    activeName: String
  },
  computed: {
    publicData() {
      return this.$store.state.user.myData ? this.$store.state.user.myData.publicKeyData : ''
    },
    privateData() {
      return this.$store.state.user.myData ? this.$store.state.user.myData.privateKeyData : ''
    },
    teamId() {
      return this.$store.state.team.teamId
    }
  },
  mounted() {
    this.$store.commit('user/SET_PUBLIC', '')
  },
  watch: {
    teamId:{
      deep: true,
      handler: function(newV, oldV) {
        this.teamId = newV
      }
    }
  },
  computed: {
    teamId(){
      return this.$store.state.team.teamId
    }
  },
  methods: {
    test() {
      window.open('https://app.searchads.apple.com/cm/app/settings/apicertificates')
    },
    // 获取公钥和私钥
    async getSecretKey() {
      let data = {
        teamUid: this.teamId
      }
      const res = await createSecretKey(data)
      if (res.data.code === 20000) {
        this.form.pubKey = res.data.data.publicKeyData
        this.form.priKey = res.data.data.privateKeyData
        this.form.uuid = res.data.data.uuid
      } else if (res.data.code === 20008) {
        this.form.pubKey = res.data.data[0].publicKeyData
        this.form.priKey = res.data.data[0].privateKeyData
        this.form.uuid = res.data.data[0].uuid
      } else {
        this.$message.error('生成密钥失败')
      }
    },
    copyText() {
      const clipboard = new Clipboard('.copy_text')
      clipboard.on('success', e => {
        this.$message.success('复制成功')
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        this.$message.success('复制失败')
        clipboard.destroy()
      })
    },
    // 绑定证书
    bindZS(form) {
       if(!this.form.pubKey || !this.form.priKey ) return this.$message.error('请生成密钥')
      this.$refs[form].validate(async valid => {
        if (this.$store.state.user.myData) {
          this.form.uuid = this.$store.state.user.myData.uuid
        }
        const data = {
          clientId: this.form.clientId,
          teamId: this.form.teamId,
          keyId: this.form.keyId,
          secretName: this.form.name,
          uuid: this.form.uuid,
          teamUid: this.teamId
        }
        if (valid) {
          this.$forceUpdate()
          this.isStatus = true
          try{
            const res = await bindModify(data)
            if (res.data.code === 20000) {
            this.$message.success('绑定证书成功,请稍后...')
            setTimeout(()=>{
              this.$router.push('/user/zs_manager')
              this.form.clientId = ''
              this.form.teamId = ''
              this.form.keyId = ''
              this.form.name = ''
              this.form.uuid = ''
              this.form.pubKey = ''
              this.form.priKey = ''
              this.$store.commit('user/SET_PUBLIC', '')
              this.isStatus = false
              this.$forceUpdate()
            }, 5000)
          } else {
            this.isStatus = false
            this.$message.error(res.data.message || '绑定证书失败')
            this.$forceUpdate()
          }
          } catch(err)  {
           this.$message.error(err)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";
div /deep/.el-form--label-top .el-form-item__label {
  line-height: 0px;
}
.header {
  width: 100%;

  height: 70px;
  position: fixed;
  // left: 0;
  margin-top: -25.0px;
  z-index: 99;
  background: #f9f9f9;
  .header_span {
    position: absolute;
    margin-top: 24px;
    // margin-left: 105px;
  }
}
.zs_bind_back {
  cursor: pointer;
  font-size: 20px;
  font-weight: bold;
}
.el-icon-left {
  color: $backColor1;
  font-weight: bold;
}
.fin_header{
  span {
    font-size: 20px;
    text-indent: 18px;
    position: relative;
    margin-left: 5px;
    font-family: "PingFangSC-Medium", PingFangSC, sans-serif !important;
    top: 30px;
    //  &::after {
    //   display: inline-block;
    //   content: '1';
    //   width: 8px;
    //   height: 24px;
    //   position: absolute;
    //   top: 12px;
    //   left: 0px;
    //   transform: translateY(-50%);
    //   font-size: 0;
    //   background-color: $mainColor1;
    // }
  }
}
.form {
  .el-input {
    width: 60%;
    margin-top:8px;
  }
  .key_text {
    position: absolute;
    margin-top: 3px;
    right:58%;
    text-align: right;
    cursor: pointer;
    color: $mainColor1;
  }
    .copy_text {
    position: absolute;
    right: 58%;
    margin-top: 45px;
    text-align: right;
    color: $mainColor1;
    z-index: 1;
    cursor: pointer;
  }
  .bind_button {
    background: #ACB6C2;
    color: #fff;
  }
}
.content-top{
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 40px;
}
.content-top-left{
  width: 70%;
  margin: 0px;
  margin-top: 10px;
}
.content-top-right{
  width: 30%;
  position: relative;
  left: -15%;
  margin-top: -5px;
  label {
    color: $mainColor1;
    cursor: pointer;
  }
}
.icon_img {
  color: #C6C6C6;
  font-size: 14px;
  margin-left: -10px;
  margin-right: 5px;
}
.right_title {
  color: $mainTextColor2;
  font-size: $mainTextFont5;
  font-weight: bold;
  margin-top: 10px;
}
.right_title_text {
  color: $mainTextColor2;
  font-size: $mainTextFont5;
  font-weight: bold;
  position: relative;
  margin-top: 15px;
  font-family: 'PingFang SC';
}
.title_tip {
  color: $backColor1;
  font-size: $mainTextFont6;
  width: 465px;
  // height: 36px;
  line-height: 24px;
  font-size: 14px;
  margin-top: 10px;
  font-family: 'PingFang SC';
}
</style>
